package org.nt4b.schemadoc.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.nt4b.schemadoc.core.dom.Column;
import org.nt4b.schemadoc.core.dom.Table;


public class OutputFilter {
    
    /**
     * Function creates filtered SchemaComments object.
     * 
     * @param schemaComments
     * @param onlyTables
     * @param onlyWithComments
     * @return
     */
    public static List<Table> filter(final List<Table> tables, final CommandLine cmd) {
        final boolean onlyWithComments;
        if (cmd.hasOption(ProgrammOptions.DOCUMENTED.getOpt())) {
            onlyWithComments = true;
        } else {
            onlyWithComments = false;
        }
        
        final List<String> onlyTables;
        if (cmd.hasOption(ProgrammOptions.TABLES.getOpt())) {
            final String tablesString = cmd.getOptionValue(ProgrammOptions.TABLES.getOpt());
            final String[] tablesArray = org.springframework.util.StringUtils.delimitedListToStringArray(tablesString, ",");
            onlyTables = Arrays.asList(tablesArray);
        } else {
            onlyTables = null;
        }
        
        final List<Table> result = new ArrayList<Table>();
        for (final Table table : tables) {
            if (OutputFilter.checkFilter(table, onlyTables, onlyWithComments)) {
                result.add(table);
            }
        }
        return result;
    }
    
    /**
     * Checks whether table will be filtered.
     * 
     * @param table
     * @param onlyTables
     * @param onlyWithComments
     * @return
     */
    private static boolean checkFilter(final Table table, final List<String> onlyTables, final boolean onlyWithComments) {
        if ((onlyTables.size() > 0) && onlyTables.contains(table.getName())) {
            return false;
        }
        
        if (onlyWithComments) {
            for (final Column column : table.getColumns()) {
                if (column.getComment() != null) {
                    return true;
                }
            }
            if (table.getComment() == null) {
                return false;
            }
        }
        
        return true;
        
    }
    
}
